import { getPatientBaseObject } from '../../../../../../utils/api/patientBase'
import { addDisease } from '../../../../../../utils/api/medicalCondition'
import userBaseInfoState from '../../../../../../stores/userBaseInfo'
import { mySleep } from '../../../../../../utils/util'
import Notify from '@vant/weapp/notify/notify';
// pages/home/home-nav/medical-condition/disease-info/disease-add/index.ts

const dayLength = 31;
const dateData = {
  years: Array.from({ length: 31 }, (_, i) => `${2000 + i}`), // Years 2000-2030
  months: Array.from({ length: 12 }, (_, i) => `${i + 1}`), // Months 1-12
  days: Array.from({ length: dayLength }, (_, i) => `${i + 1}`), // Days 1-31
};

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: <PatientBaseEntity>{
      patientUid: '',
      wxUid: '',
      physicalStrength: '',
    },
    user: {
      diseases: {
        name: '请选择疾病',
        date: '请选择时间',
      }
    },
    diseaseNamesColumns: [
      '高血压',
      '血脂异常',
      '脑血管病',
      '心脏疾病',
      '肾脏疾病',
      '周围血管病',
      '视网膜病变',
      '糖尿病',
    ],
    diseaseNamesShow: false,
    dateShow: false,
    dateColumns: [
      {
        values: dateData.years,
        className: 'column1',
      },
      {
        values: dateData.months,
        className: 'column2',
      },
      {
        values: dateData.days,
        className: 'column3',
      },
    ],
    selectedDate: [0, 0, 0],
    currentDate: new Date().getTime(),
    minDate: new Date(2000, 0, 1).getTime(),
    maxDate: new Date().getTime(),
    formatter(type: string, value: any) {
      if (type === 'year') {
        return `${value}年`;
      }
      if (type === 'month') {
        return `${value}月`;
      }
      return value;
    },
  },

  diseaseShow() {
    this.setData({ diseaseNamesShow: true });
  },

  diseaseHidden() {
    this.setData({ diseaseNamesShow: false });
  },

  diseaseConfirm(event: { detail: { picker: any; value: string; index: number; } }) {
    this.setData({ 'user.diseases.name': event.detail.value });
    this.setData({ diseaseNamesShow: false });
  },

  letDateShow() {
    this.setData({ dateShow: true });
  },

  dateClose() {
    this.setData({ dateShow: false });
  },

  dateConfirm(event: { detail: { picker: any; value: string; index: number; } }) {
    console.log(event);
    const year = event.detail.value[0] as string;
    let temp = event.detail.value[1] as string;
    const month = ('0' + temp).slice(-2);
    temp = event.detail.value[2] as string;
    const day = ('0' + temp).slice(-2);
    const date = year + '-' + month + '-' + day;
    this.setData({
      'user.diseases.date': date,
      'dateShow': false
    })
  },

  onInput(event: any) {
    this.setData({
      currentDate: event.detail,
    });
  },

  onConfirm(event: any) {
    console.log(event);
    let timeStamp = event.detail;
    let date = new Date(timeStamp);
    const formattedDate = date.getFullYear() + '-' +
      String(date.getMonth() + 1).padStart(2, '0') + '-' +
      String(date.getDate()).padStart(2, '0') as string;

    console.log(formattedDate);
    this.setData({
      'dateShow': false,
      'user.diseases.date': formattedDate,
    })
  },

  dateChange(event: { detail: { value: [number, number, number] } }) {
    const [yearIndex, monthIndex, dayIndex] = event.detail.value;
    const selectedYear = parseInt(this.data.dateColumns[0].values[yearIndex]);
    const selectedMonth = parseInt(this.data.dateColumns[1].values[monthIndex]);
    const daysInMonth = this.getDaysInMonth(selectedYear, selectedMonth);

    // Update days column if necessary
    if (daysInMonth !== this.data.dateColumns[2].values.length) {
      const newDaysColumn = Array.from({ length: daysInMonth }, (_, i) => `${i + 1}`);
      this.setData({
        'columns[2].values': newDaysColumn,
        'selectedDate[2]': Math.min(dayIndex, newDaysColumn.length - 1),
      });
    } else {
      this.setData({ selectedDate: event.detail.value });
    }
  },

  getDaysInMonth(year: number, month: number): number {
    return new Date(year, month, 0).getDate();
  },

  updateUserInfo() {
    const data = <PatientBaseEntity>{ wxUid: wx.getStorageSync("openid") };
    // 如果已经获取状态信息那么无需再次获取，判断是否具有 patientUid和username即可确认
    getPatientBaseObject(data).then((res: any) => {
      // console.log('获取基本信息成功-disease-add', res);
      userBaseInfoState.onChangeData(res.data[0])
      this.setData({
        userInfo: userBaseInfoState.data
      })
    }).catch((err: any) => {
      console.log("获取基本信息失败", err);
    })
  },

  addRecord() {
    if (this.data.user.diseases.name === '请选择疾病') {
      Notify({ type: 'danger', message: '药品名称不能为空' })
      return;
    }
    if (this.data.user.diseases.date === '请选择时间') {
      Notify({ type: 'danger', message: '确诊时间不能为空' })
      return;
    }
    const data = {
      patientUid: this.data.userInfo.patientUid,
      disease: this.data.user.diseases.name,
      diseaseTime: this.data.user.diseases.date,
    }
    addDisease(data).then(async (res: any) => {
      console.log('添加疾病成功', res);
      await mySleep(500)
      wx.navigateBack({
        delta: 1
      })
    }).catch((err: any) => {
      console.log('添加疾病失败', err);
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    this.updateUserInfo();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})